// 文章数据模型

const PostType = require('../postType/models.js')
const PostTag = require('../postTag/models.js')
const User = require('../user/models.js')
const mongoose = require('mongoose')
const shortid = require('shortid')
const moment = require('moment')
const sConf = require('../../config/staticConfig.js')

const Schema = mongoose.Schema

const PostSchema = new Schema({
  // 数据库中存储ID
  _id: {
    type: String,
    'default': shortid.generate
  },
  title: String,        // 标题
  subtitle: String,    // 二级标题
  cover: String,        // 图片
  description: String,  // 简介
  content: String,      // 文章内容
  // 内容格式 0：markdown 1：Text
  contenttype: {
    type: String,
    default: sConf.contentType[0]
  },
  author: {
    type: String,
    ref: 'User'
  },
  // 分类
  posttype: [
    {
      type: String,
      ref: 'PostType'
    }
  ],
  // 权限 0:public 1:secret
  auth: {
    type: String,
    default: sConf.contentAuth[0]
  },
  // 文章状态 0:published 发布 1:draft 草稿
  state: {
    type: String,
    default: sConf.contentState[0]
  },
  // 是否置顶推荐
  istop: {
    type: Boolean,
    default: false
  },
  // 文章来源 0: original原创 1: reprint转载
  from: {
    type: Number,
    default: sConf.contentFrom[0]
  },
  // 文章标签
  tags: [
    {
      type: String,
      ref: 'PostTag'
    }
  ],
  // 评论次数
  commentscounts: {
    type: Number,
    default: 0
  },
  // 喜欢次数
  likescounts: {
    type: Number,
    default: 0
  },
  // 浏览次数
  clickscounts: {
    type: Number,
    default: 0
  },
  // 收藏次数
  collectionscounts: {
    type: Number,
    default: 0
  },
  // 签到次数
  signincounts: {
    type: Number,
    default: 0
  },
  // 喜欢该文章的用户列表
  likeusers: [
    {
      type: String,
      default: []
    }
  ],
  // 收藏该文章的用户列表
  collectusers: [
    {
      type: String,
      default: []
    }
  ],
  create_time: {
    type: Date,
    default: Date.now
  },
  modify_time: {
    type: Date,
    default: Date.now
  }
})

PostSchema.set('toJSON', { getters: true, virtuals: true })
PostSchema.set('toObject', { getters: true, virtuals: true })

PostSchema.path('create_time').get(function (v) {
  return moment(v).utc().utcOffset(-8).format("YYYY-MM-DD")
})
PostSchema.path('modify_time').get(function (v) {
  return moment(v).utc().utcOffset(-8).format("YYYY-MM-DD")
})

module.exports = mongoose.model('Post', PostSchema)
